package com.xiaoka.ins.corp.api.utils;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.RandomUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * @author zheng
 *
 *         工具类
 */
public class BaseUtils {

	/**
	 * @return 唯一标识
	 * 
	 */
	public static String getUniqueId() {
		SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return timeFormat.format(new Date()) + RandomUtils.nextInt(1000, 9999);
	}

	public static String filterJson(String json) {
		if (!json.startsWith("({")) {
			json = json.substring(json.indexOf("({"), json.length());
		}
		if (json.startsWith("(") && json.endsWith(")")) {
			json = json.substring(1, json.length() - 1);
		}
		return json;
	}

	/**
	 * 
	 * 获取两字符之间字符串
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String getBetweenStr(String str, String start, String end) {
		start = start.contains("(") ? start.replace("(", "\\(") : start;
		end = end.contains(")") ? end.replace(")", "\\)") : end;
		Matcher m = Pattern.compile(start + "(.*?)" + end).matcher(str);
		while (m.find()) {
			return m.group(1);
		}
		return "";
	}

	/**
	 * 根据身份证获取生日，返回格式：1990-01-01
	 * 
	 * @param ID
	 * @return
	 */
	public static String getFormatBirthday(String ID) {
		if (ID == null) {
			throw new NullPointerException("ID must not be null");
		}
		String birthday = ID.substring(ID.length() - 12, ID.length() - 4);
		birthday = birthday.substring(0, 4) + "-" + birthday.substring(4, 6)
				+ "-" + birthday.substring(6, birthday.length());
		return birthday;
	}

	/**
	 * 根据身份证获取生日，返回格式：0605
	 * 
	 * @param ID
	 * @return
	 */
	public static String getBirthdayByID(String ID) {
		if (ID == null) {
			throw new NullPointerException("ID must not be null");
		}
		return ID.substring(ID.length() - 8, ID.length() - 4);
	}

	/**
	 * 根据身份证判断性别：1为男，0为女
	 * 
	 * @param ID
	 * @return
	 */
	public static String getGenderByID(String ID) {
		if (ID == null) {
			throw new NullPointerException("ID must not be null");
		}
		String sex = ID.substring(16, 17);
		return Integer.parseInt(sex) % 2 == 0 ? "0" : "1";
	}

	/**
	 * 在原有时间增加一年
	 * 
	 * @param date
	 * @return
	 */
	public static Date addDate(Date date, int num, DateEnum dateEnum) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		switch (dateEnum) {
		case Year:
			cal.add(Calendar.YEAR, num);
			cal.add(Calendar.DATE, -1);
			break;
		case Month:
			cal.add(Calendar.MONTH, num);
			break;
		case Day:
			cal.add(Calendar.DATE, num);
			break;
		default:
			break;
		}
		return cal.getTime();
	}

	/**
	 * 
	 * 获取两个时间相差的年数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getDifferYear(Date date1, Date date2, DateEnum dateEnum) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(date1);
		c2.setTime(date2);
		int ret1, ret2;
		switch (dateEnum) {
		case Year:
			ret1 = c1.get(Calendar.YEAR);
			ret2 = c2.get(Calendar.YEAR);
			return Math.abs(ret1 - ret2);
		case Month:
			ret1 = c1.get(Calendar.MONTH);
			ret2 = c2.get(Calendar.MONTH);
			return Math.abs(ret1 - ret2);
		default:
			break;
		}
		return 0;
	}

	/**
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dateFormat(Date date, String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.format(date);
	}

	public static Date toDate(String str) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(str);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加小数点
	 * 
	 * @param str
	 * @return
	 */
	public static String addDecimalPoint(String str) {
		if (str == null) {
			throw new NullPointerException("字符串不能为空");
		} 
		return str.length()>2?str.substring(0, str.length() - 2) + "."
				+ str.substring(str.length() - 2, str.length()):str;
	}

	/**
	 * 删除小数点
	 * 
	 * 例：11.00 删除小数点后就是11
	 * 
	 * @param str
	 * @return
	 */
	public static String deleteDecimalPoint(String str) {
		if (str == null) {
			throw new NullPointerException("字符串不能为空");
		} else if (str.length() < 2) {
			throw new StringIndexOutOfBoundsException("字符串长度不能小于2");
		} else if (str.contains(".")) {
			str = new BigDecimal(str).intValue() + "";
		}
		return str;
	}

	/**
	 * 根据文件名获取文件对象
	 * 
	 * @param filename
	 * @return
	 */
	public static File getFileByName(String filename) {
		if (filename == null) {
			throw new NullPointerException("filename must not be null");
		}
		String filePath = BaseUtils.class.getClassLoader()
				.getResource(filename).getPath();
		if (filePath.startsWith("/")) {
			filePath = filePath.substring(1, filePath.length());
		}
		return new File(filePath);
	}

	public static BigDecimal toDecimal(Object val) {
		BigDecimal bd=new BigDecimal(val.toString());   
		bd=bd.setScale(2, BigDecimal.ROUND_HALF_UP);   
		return bd;
	}

	public static BigDecimal toDepreciation(BigDecimal purchasePriceTax,
			Date firstReg, Date begin) {
		int month = getDifferYear(begin, firstReg, DateEnum.Month);
		//折旧价=新车购置价-(新车购置价*月折旧率*月份)
		double actPrice = purchasePriceTax.floatValue() - (purchasePriceTax.floatValue() * month * 0.06);
		//折旧价最低不能低于2折
		 if (actPrice < purchasePriceTax.floatValue() * 0.2) 
		 { 
			 actPrice = purchasePriceTax.floatValue() * 0.2; 
		 }
		return toDecimal(actPrice);
	}
	
	public static <T> String beanToXml(T entity, Class<?> cls)
	{
		XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder()));
		xStream.processAnnotations(cls);
		xStream.autodetectAnnotations(true);
		return xStream.toXML(entity);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T xmlToBean(String xml, Class<?> cls)
	{
		XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder()));
		xStream.processAnnotations(cls);
		xStream.autodetectAnnotations(true);
		return (T)xStream.fromXML(xml);
	}
}
